<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\DB;
use App\Console\Commands\WdtClient;
use Illuminate\Support\Str;

/**
 * 批量推送商品档案到旺店通ERP 5min 非组合商品
 * 执行命令：php artisan sync:GoodsPush
 * 文档：https://open.wangdian.cn/open/apidoc/doc?path=goods_push.php
 */
class SyncGoodsPush extends Command
{
    protected $signature = 'sync:GoodsPush';
    protected $description = '批量推送商品档案到旺店通ERP';

    public function handle()
    {
        Log::info('同步任务SyncGoodsPush', ['开始推送goods商品档案到旺店通']);
        $sid = config('services.wdt.sid');
        $appkey = config('services.wdt.appkey');
        $secret = config('services.wdt.secret');
        $url = config('services.wdt.url') . 'goods_push.php';

        $c = new WdtClient($sid, $appkey, $secret, $url);

        // 1. 查询所有上架商品
        //单个商品长传
//        $goodsList = DB::table('goods')->where('id',146)->where('status', 1)->get();
        $goodsList = DB::table('goods')->where(['status'=>1,'is_group'=>0])->get();
        $total = $goodsList->count();
        $this->info('goods上架商品总数: ' . $total);

        $batchSize = 50; // 官方建议每批不超过50
        $goodsArr = $goodsList->toArray();
        $batches = array_chunk($goodsArr, $batchSize);

        foreach ($batches as $batch) {
            $goodsListArr = [];
            foreach ($batch as $good) {
                // goods_list
                $goodsListArr[] = [
                    'goods_no'    => $good->goods_sn,
                    'goods_type'  => 1, // 默认1销售商品
                    'goods_name'  => $good->goods_name,
                    'short_name'  => $good->goods_name,
                    'alias'      => '',
                    'pinyin'     => '',
                    'origin'     => '',
                    'class_name'  => (string)$good->goods_type,
                    'brand_name'  => $good->goods_supplier,
                    'unit_name'   => $good->goods_unit,
                    'remark'     => $good->goods_remark,
                    // spec_list
                    'specList'   => [[
                        'spec_no'            => $good->goods_sn."_".$good->goods_unit."_".$good->goods_specification,
                        'spec_code'          => $good->goods_specification,
                        'barcode'           => $good->goods_sn."_".$good->goods_unit."_".$good->goods_specification,
                        'spec_name'          => $good->goods_specification,
                        'is_allow_neg_stock'   => 1,
                        'weight'            => $good->goods_weight_m,
                        'retail_price'            => $good->goods_price,
                    ]],
                ];
            }

            // 小驼峰转下划线（旺店通接口要求参数为下划线风格）
            $goodsListArrSnake = array_map(function ($item) {
                $itemSnake = [];
                foreach ($item as $k => $v) {
                    $itemSnake[Str::snake($k)] = $v;
                }
                // spec_list 也要转
                if (isset($itemSnake['spec_list'])) {
                    $itemSnake['spec_list'] = array_map(function ($spec) {
                        $specSnake = [];
                        foreach ($spec as $sk => $sv) {
                            $specSnake[Str::snake($sk)] = $sv;
                        }
                        return $specSnake;
                    }, $itemSnake['spec_list']);
                }
                return $itemSnake;
            }, $goodsListArr);

            $goodsListJson = json_encode($goodsListArrSnake, JSON_UNESCAPED_UNICODE);
            $c->putApiParam('goods_list', $goodsListJson);

            Log::info('推送旺店通商品档案参数', [$goodsListJson]);
            $result = $c->wdtOpenApi();
            Log::info('旺店通商品档案推送结果', [$result]);
        }

        $this->info('商品档案推送任务执行完毕');
    }
} 